package com.adtec.base.cloud.xxljobservise.xxljob.xxljob.utils;

import com.adtec.base.cloud.xxljobservise.xxljob.xxljob.model.Datasource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;

@Component
public class ExecuteSQLUtil {

    @Resource
    private Datasource datasource;

    public Connection executeSql(String sqlFileName) {
        Connection connection = null;
        try {
            String driverClassName = "com.mysql.cj.jdbc.Driver";
            Class.forName(driverClassName);
            connection = DriverManager.getConnection(datasource.getUrl(), datasource.getUsername(), datasource.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileSystemResource rc = new FileSystemResource(sqlFileName);
//        ClassPathResource rc = new ClassPathResource(sqlFileName);
        EncodedResource er = new EncodedResource(rc, "utf-8");
        ScriptUtils.executeSqlScript(connection, er);
        return connection;
    }
}